package com.ruanyun.modular.app.service.impl;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.aliyuncs.exceptions.ClientException;
import com.ruanyun.api.core.util.JwtTokenUtil;
import com.ruanyun.base.pojo.page.LayuiPageFactory;
import com.ruanyun.base.pojo.page.LayuiPageInfo;
import com.ruanyun.modular.admin.entity.*;
import com.ruanyun.modular.admin.mapper.*;
import com.ruanyun.modular.admin.model.params.TMeasuresParam;
import com.ruanyun.modular.admin.model.result.*;
import com.ruanyun.modular.admin.service.*;
import com.ruanyun.modular.app.entity.TUser;
import com.ruanyun.modular.app.mapper.TUserMapper;
import com.ruanyun.modular.app.model.params.TUserParam;
import com.ruanyun.modular.app.model.result.TUserResult;
import  com.ruanyun.modular.app.service.TUserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanyun.sys.modular.system.entity.User;
import com.ruanyun.sys.modular.system.model.result.CountyResult;
import com.ruanyun.sys.modular.system.service.UserService;
import com.ruanyun.util.AliYunMessage;
import com.ruanyun.util.MD5Utils;
import com.ruanyun.util.RandomStringUtils;
import com.ruanyun.util.aliyun;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-04-20
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TBasicinfoMapper basicinfoMapper;
    @Autowired
    private  TCommitReportMapper commitReportMapper;
    @Autowired
    private TBasicMaterialService basicMaterialService;
    @Autowired
    private TExhaustEquipmentService exhaustEquipmentService;
    @Autowired
    private TMonitoringinfoService monitoringinfoService;
    @Autowired
    private TProductEquipmentService productEquipmentService;
    @Autowired
    private TProductinfoService productinfoService;
    @Autowired
    private  TProductionProcessService productionProcessService;
    @Autowired
    private  TProposedMeasuresPlanService proposedMeasuresPlanService;
    @Autowired
    private  VocManagementLedgerService vocManagementLedgerService;
    @Autowired
    private  VocsEmissionService vocsEmissionService;
    @Autowired
    private UserService userService;
    @Autowired
    private VocReducingPlanService vocReducingPlanService;
    @Autowired
    private TExhaustOrificeService tExhaustOrificeService;
    @Autowired
    private  TMeasuresService measuresService;

    @Autowired
    private  TPollutantsFactorService pollutantsFactorService;




    @Override
    public ResponseData add(TUserParam param){
        TUser entity = getEntity(param);
        int result = this.baseMapper.insert(entity);
        if(result == 0){
            return ResponseData.error("添加失败");
        }
        return ResponseData.success();
    }

    @Override
    public void delete(TUserParam param){
        this.removeById(getKey(param));
    }

    /**
    * 删除
    *
    * @param id
    * @return
    */
    @Override
    public ResponseData updateDelFlagById(Long id) {
        TUser entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该用户表不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("删除失败");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData update(TUserParam param){
        TUser oldEntity = getOldEntity(param);
        TUser newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        int result = this.baseMapper.updateById(newEntity);
        if(result == 0){
        return ResponseData.error("修改失败失败");
        }
        return ResponseData.success();
    }

    @Override
    public TUserResult findBySpec(TUserParam param){
        return null;
    }

    @Override
    public List<TUserResult> findListBySpec(TUserParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(TUserParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(TUserParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private TUser getOldEntity(TUserParam param) {
        return this.getById(getKey(param));
    }

    private TUser getEntity(TUserParam param) {
        TUser entity = new TUser();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    /**
        * 启用
        *
        * @param id
        * @return
        */
    @Override
    public ResponseData enableById(Long id) {
        TUser entity = this.baseMapper.selectById(id);
        if (entity == null) {
        return ResponseData.error("该用户表不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("启用失败");
        }
        return ResponseData.success();
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData disableById(Long id) {
        TUser entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该用户表不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("禁用失败");
        }
        return ResponseData.success();
    }



    /*注册接口*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData register(String phone, String pwd, String code, String socialCode,String pid) {

        if(ToolUtil.isEmpty(pid)){
            return ResponseData.error("请选择所属县");
        }

        //判断是否注册过了
        TUserResult userResult = baseMapper.getUserByPhone(phone);
        if(!ToolUtil.isEmpty(userResult)){
            return ResponseData.error("该用户已注册，请直接登录！");
        }


        //获取redis中的验证码
        String codeVal = redisTemplate.opsForValue().get(phone);
        if(ToolUtil.isEmpty(codeVal)){
            return ResponseData.error("验证码不存在或已过期！");
        }else if(!code.equals(codeVal)){
            return ResponseData.error("验证码错误！");
        }
        TUser user = addUser(phone,pwd,socialCode,pid);

           //添加后端用户
           userService.insertCompany(phone,pwd,pid);


        return ResponseData.success("注册成功");
    }

    @Override
    public ResponseData getCode(String phone, String type) throws ClientException {
        //根据手机号查询用户数量
        TUserResult userResult = baseMapper.getCountByPhone(phone);

        //注册 获取手机号查询是否注册过了
        if("1".equals(type) && !ToolUtil.isEmpty(userResult)){
            return ResponseData.error("用户已存在，请直接登录！");
        }

        //修改密码
        if("2".equals(type) && ToolUtil.isEmpty(userResult)){
            return ResponseData.error("用户未注册，请先注册！");
        }

        //修改支付密码
        if("3".equals(type) && ToolUtil.isEmpty(userResult)){
            return ResponseData.error("用户未注册，请先注册！");
        }else if("3".equals(type) && !phone.equals(userResult.getPhone())){
            return ResponseData.error("手机号码有误，请填写注册手机号！");
        }

        //修改手机号
        if("4".equals(type) && !ToolUtil.isEmpty(userResult)){
            return ResponseData.error("不能与原手机号相同！");
        }

        //获取随机数
        String code = RandomStringUtils.randomStr();
        //type为1是注册，为2是忘记密码，3是个人验证码登录, 4是修改手机号
        AliYunMessage.sendSms(phone, code, type);
        //设置redis缓存一分钟
        redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
        //存入数据库用于后面验证
        Map<String,Object> map = new HashMap<>();
        map.put("phone",phone);
        map.put("keyVal",code);
        baseMapper.addPhoneKey(map);
        return ResponseData.success(200,"发送短信成功",code);

    }



    private TUser addUser(String phone,String pwd,String socialCode,String pid){
        //没有注册过就添加用户
        TUser user = new TUser();
        user.setUserName(phone);
        user.setNickname(phone);
        user.setPhone(phone);
        user.setSocialCreditCode(socialCode);
        user.setPassword(MD5Utils.encrypt(pwd));
        user.setPid(pid);
        this.save(user);
        return user;
    }

    @Override
    public ResponseData login(String phone, String pwd) {
        Map map = new HashMap();
        //判断是否注册过了
        TUserResult userResult = baseMapper.getUserByPhone(phone);
        //判断是否可以登录
        if(ToolUtil.isEmpty(userResult)){
            return ResponseData.error("用户未注册，请先注册！");
        }
        if(userResult.getStatus() == 2){
            return ResponseData.error("您的账户已被冻结！");
        }
        if(!MD5Utils.encrypt(pwd).equals(userResult.getPassword())){
            return ResponseData.error("密码错误！");
        }
        //生成token返回
        String token = JwtTokenUtil.generateToken(String.valueOf(userResult.getId()));
        userResult.setToken(token);
        return ResponseData.success(userResult);

    }


    @Override
    public ResponseData updatePwd(String userId, String phone, String code,String newPwd) {
        TUser user = baseMapper.selectById(userId);
        if(!user.getPhone().equals(phone)){
            return ResponseData.error("请填写用户注册手机号!");
        }
        String s = redisTemplate.opsForValue().get(phone);
        if (s==null){
            return ResponseData.error("对不起,验证码已过期！");
        }else if(!s.equals(code)){
            return ResponseData.error("验证码错误！");
        }
        if(MD5Utils.encrypt(newPwd).equals(user.getPassword())){
            return ResponseData.error("新密码不能与原密码相同!");
        }
        user.setPassword(MD5Utils.encrypt(newPwd));
        this.updateById(user);
        return ResponseData.success("操作成功!");
    }

    @Override
    public ResponseData forgetPwd(String phone, String code, String newPwd) {
        //根据手机号查询用户数量
        TUserResult userResult = baseMapper.getCountByPhone(phone);
        if(ToolUtil.isEmpty(userResult)){
            return ResponseData.error("用户未注册，请先注册！");
        }
        String s = redisTemplate.opsForValue().get(phone);
        if (s==null){
            return ResponseData.error("对不起,验证码已过期！");
        }else if(!s.equals(code)){
            return ResponseData.error("验证码错误！");
        }
        if(MD5Utils.encrypt(newPwd).equals(userResult.getPassword())){
            return ResponseData.error("新密码不能与原密码相同!");
        }
        TUser user = new TUser();
        BeanUtils.copyProperties(userResult,user);
        user.setPassword(MD5Utils.encrypt(newPwd));
        this.updateById(user);
        return ResponseData.success("操作成功!");
    }


    @Override
    public ResponseData bindingPhone(String userId, String oldPhone, String newPhone, String code) {
        if(oldPhone.equals(newPhone)){
            return ResponseData.error("新手机号与原手机号不能相同！");
        }
        //获取旧手机号
        TUser user = baseMapper.selectById(userId);
        if(!user.getPhone().equals(oldPhone)){
            return ResponseData.error("原手机号错误!");
        }
        String s = redisTemplate.opsForValue().get(newPhone);
        if (s==null){
            return ResponseData.error("对不起,验证码已过期！");
        }else if(!s.equals(code)){
            return ResponseData.error("验证码错误！");
        }
        //修改用户
        user.setPhone(newPhone);
        user.setUserName(newPhone);
        baseMapper.updateById(user);
        return ResponseData.success("绑定成功！");
    }


    @Override
    public ResponseData updateUser(TUserParam userParam) {
        //判断是否修改手机号
        if(!ToolUtil.isEmpty(userParam.getPhone())){
            //查询用户信息
//            User user = this.baseMapper.selectById(userParam.getId());
//            if(!user.getPhone().equals(userParam.getPhone())){
//                return ResponseData.error("旧手机号错误！");
//            }
            //判断验证码是否存在
            if(ToolUtil.isEmpty(userParam.getCode())){
                return ResponseData.error("验证码不能为空！");
            }
            String s = redisTemplate.opsForValue().get(userParam.getPhone());
            if (s==null){
                return ResponseData.error("对不起,验证码已过期！");
            }else if(!s.equals(userParam.getCode())){
                return ResponseData.error("验证码错误！");
            }
        }else {
            userParam.setPhone(null);
        }
        //修改密码
        if(!ToolUtil.isEmpty(userParam.getPassword())){
            userParam.setPassword(MD5Utils.encrypt(userParam.getPassword()));
        }
        TUser user = new TUser();
        BeanUtils.copyProperties(userParam,user);
        baseMapper.updateById(user);
        return ResponseData.success("修改成功！");
    }

    @Override
    public ResponseData getCommit(String userId) {
          TUser tUser = baseMapper.selectById(userId);
          String sid =tUser.getSocialCreditCode();
         //获取企业信息
          TBasicinfo basicinfo = basicinfoMapper.getDetailInfo(sid);

         if(basicinfo != null){
             Integer cid = basicinfo.getId();
             TBasicinfoResult basicinfoResult = new TBasicinfoResult();

             /*获取提交信息表数据*/
             TCommitReport commitReport = commitReportMapper.getCommit(cid);
             if(commitReport != null){
                 ToolUtil.copyProperties(basicinfo,basicinfoResult);
                  basicinfoResult.setPollutionPermitDates(basicinfo.getPollutionPermitDate());
                 return ResponseData.success(basicinfoResult);
             } else {
                 return  ResponseData.error("该用户信息尚未提交完善");
             }
         }

        return  ResponseData.error("该用户信息尚未提交完善");
    }

    @Override
    public ResponseData getCommitOther(String userId, Integer type,Integer emissionWay,Integer planType) {


        TUser tUser = baseMapper.selectById(userId);
        String sid =tUser.getSocialCreditCode();
        //获取企业信息
        TBasicinfo basicinfo = basicinfoMapper.getDetailInfo(sid);

        if(basicinfo != null){
             //获取企业id
            Integer cid = basicinfo.getId();

            /*获取提交信息表数据*/
            TCommitReport commitReport = commitReportMapper.getCommit(cid);
            if(commitReport != null){
                if(type == 2){
                    //获取主要原辅料信息
                    Page<TBasicMaterialResult> tBasicMaterialResultPage = basicMaterialService.getMateriaPage(cid);
                    return ResponseData.success(tBasicMaterialResultPage);

                }  else if(type == 6){
                    //获取废气治理设施信息
                    Page<TExhaustEquipmentResult> exhaustEquipmentPage = exhaustEquipmentService.getExhaustEquipmentPage(cid);
                    return ResponseData.success(exhaustEquipmentPage);

                } else if(type ==5){
                    // 获取废气排放口信息
                    Page<TExhaustOrificeResult> exhaustPage = tExhaustOrificeService.getExhaustPage(cid);
                    return ResponseData.success(exhaustPage);
                } else  if(type == 7){
                     //获取监测信息
                     Page<TMonitoringinfoResult> monitoringinfoResultPage = monitoringinfoService.getMonitoringinfoPage(cid);
                    return ResponseData.success(monitoringinfoResultPage);
                } else  if(type == 3){
                    //获取生产设备信息
                      Page<TProductEquipmentResult> productEquipmentResultPage =  productEquipmentService.getProductEquipmentPage(cid);
                      return ResponseData.success(productEquipmentResultPage);
                } else  if(type == 1){
                    //获取产品产量
                    Page<TProductinfoResult> productinfoResultPage =  productinfoService.getProductinfoPage(cid);
                    return ResponseData.success(productinfoResultPage);
                } else  if(type ==4){

                    //获取生产工艺
                    Page<TProductionProcessResult> productionProcessPage =  productionProcessService.getProductionProcessPage(cid);
                    return ResponseData.success(productionProcessPage);
                } else  if(type ==11 ){
                     if(planType == 1){
                         //获取措施计划
                         Page<TMeasuresResult> planPage =  proposedMeasuresPlanService.getProposedMeasuresPlanPage(cid);
                         return ResponseData.success(planPage);
                     } else if(planType == 2){
                         Page<VocManagementLedgerResult> resultPage = proposedMeasuresPlanService.getLedgerPage(cid);
                         return ResponseData.success(resultPage);
                     }

                }else  if (type == 9){
                    //获取台账信息
                    Page<VocManagementLedgerResult> vocManagementLedgerPage =  vocManagementLedgerService.getVocManagementLedgerPage(cid);
                    return ResponseData.success(vocManagementLedgerPage);

                }else  if(type == 10){

                    //获取vocs排量
                    Page<VocsEmissionResult> vocsEmissionResultPage =vocsEmissionService.getVocsEmissionPage(cid,emissionWay);
                    return ResponseData.success(vocsEmissionResultPage);

                }else  if(type == 8){
                    //获取vocs综合减排措施
                    Page<VocReducingPlanResult> vocReducingPlanResultPage =vocReducingPlanService.getVocReducingPage();
                    return ResponseData.success(vocReducingPlanResultPage);

                }


                return ResponseData.success();
            } else {
                return  ResponseData.error("该用户信息尚未提交完善");
            }
        }

        return  ResponseData.error("该用户信息尚未提交完善");
    }

    @Override
    public ResponseData getVocsRedPlan(String userId, Integer redType,Integer measureType) {
        TUser tUser = baseMapper.selectById(userId);
        String sid =tUser.getSocialCreditCode();
        //获取企业信息
        TBasicinfo basicinfo = basicinfoMapper.getDetailInfo(sid);
         if(basicinfo != null){
             /*获取提交信息表数据*/
             Integer cid = basicinfo.getId();
             TCommitReport commitReport = commitReportMapper.getCommit(cid);
              if(commitReport != null){
                  Integer rid = vocReducingPlanService.getIdByCid(cid);
                  TMeasuresParam measuresParam = new TMeasuresParam();
                         measuresParam.setRedId(rid); //每个企业对应一条总的综合措施
                         measuresParam.setRedType(redType); //减排类型  源头 过程 末端
                         measuresParam.setMeasureType(measureType); //  强制性  推荐性
                  Page<TMeasuresResult> resultPage = measuresService.getMeasurePage(measuresParam);
                   return ResponseData.success(resultPage);

              }
             return  ResponseData.error("该用户信息尚未提交完善");
         }
        return  ResponseData.error("该用户信息尚未提交完善");
    }

    @Override
    public ResponseData getOrganizedInfo(Integer monitoringId, Integer isOrganization) {
           //获取该条监测信息下的排放口信息
       Page<TPollutantsFactorResult> resultPage = pollutantsFactorService.getOrganizedInfo(monitoringId,isOrganization);
        return ResponseData.success(resultPage);
    }

    @Override
    public ResponseData getOrganizedPollutantsInfo(Integer monitoringId, Integer isOrganization, Integer orificeId) {

        //获取该条监测信息下的排放口信息
        Page<TPollutantsFactorResult> resultPage =pollutantsFactorService.getOrganizedPollutantsInfo(monitoringId,isOrganization,orificeId);
        return ResponseData.success(resultPage);

    }

    @Override
    public ResponseData getUnorganizedLocationInfo(Integer monitoringId, Integer isOrganization) {
        //获取有组织污染物信息
        Page<TPollutantsFactorResult> resultPage = pollutantsFactorService.getUnorganizedLocationInfo(monitoringId,isOrganization);
        return ResponseData.success(resultPage);
    }

    @Override
    public ResponseData getInsidePollutantsInfo(Integer monitoringId, Integer isOrganization, Integer id) {
        //获取厂内污染物信息
        Page<TPollutantsFactorResult> resultPage = pollutantsFactorService.getInsidePollutantsInfo(monitoringId,isOrganization,id);
        return ResponseData.success(resultPage);


    }

    @Override
    public ResponseData getUnInsidePollutantsInfo(Integer monitoringId, Integer isOrganization, Integer windType) {

        //获取厂界污染物信息
        Page<TPollutantsFactorResult> resultPage = pollutantsFactorService.getUnInsidePollutantsInfo(monitoringId,isOrganization,windType);
        return ResponseData.success(resultPage);

    }

    @Override
    public List<CountyResult> getCountyList() {
        return userService.getCountyList();
    }

}
